package io.codegeneratetool.util.validate;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

 

/**
 * 说明：责任链模式. 
 * 	组装链 见 @link(ValidateAnnotationUtil#constructChain)
 */
public abstract class BaseProcessorChain<ANNOTATION extends Annotation> implements AnnotationProcesser{
	 
	private Logger log = LoggerFactory.getLogger(getClass());
	private BaseProcessorChain<?> nextChain;
 
	@SuppressWarnings("unchecked")
	private Class<ANNOTATION> getAnnoTationClass(){
		return   (Class<ANNOTATION>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	
	public <T> void doProcess(T t ,Field field  , Map<String, Object> validateContainer , Map<String, Object> messages){
		
		Class<ANNOTATION> annoTationClass = getAnnoTationClass();
		Annotation annotation =  field.getAnnotation(annoTationClass);
		if(annotation!=null){
			try {
				//执行本次处理
				this.process(t, field , validateContainer, messages);
				log.debug(this.getClass().getName() + " 处理 process ");
			} catch (Exception e) {
				log.error("BaseProcessorChain --> doProcess : ",e);
			}
		} else{
			log.debug( "无注解: "+ annotation);
		}
		//继续链条的下一节
		 if(this.nextChain!=null){
			 nextChain.doProcess(t, field , validateContainer, messages);
		 }
	}
	
	
	/**
	 * 说明：获取说明文本 , 如果是默认的hibernate说明,则替换成 defaultMessage
	 * @author jiaxf 创建时间2012-10-25上午11:04:09
	 * @param 
	 */
	protected String getMessage(String annotationDefaltMessage,String defaultMessage){
		if(annotationDefaltMessage==null){
			return defaultMessage;
		}
		if(annotationDefaltMessage.contains("org.hibernate.validator") || annotationDefaltMessage.contains("javax.validation")){
			return defaultMessage;
		}else{
			return annotationDefaltMessage;
		}
	}
	 
	/**  
	 * 获取chain  
	 * @return chain chain  
	 */
	public AnnotationProcesser getChain() {
		return nextChain;
	}







	/**
	 * 设置chain  
	 *	@param chain chain  
	 */
	public   void setNextChain(BaseProcessorChain<?> chain){
		this.nextChain = chain;
	}
	
	
	
	
	
	
	
	
	
}
